import yamail
import requests
import time
import hmac
import hashlib
import base64
import urllib.parse
import traceback

password="ogcdbxrrbfiybeic"
host="smtp.qq.com"
user="925182968@qq.com"
to = ["925182968@qq.com","wangxiaoyan60@qq.com"]
cc = []
url = "https://oapi.dingtalk.com/robot/send?access_token=ea67b3129ba5b6d54b186af690023b0290800075d6dfa46caf8eca68fca5ccb7"



def send_mail(subject,content,files=None):
    try:
        smtp = yamail.SMTP(host=host,
                           user=user,
                           password=password,
                           )
        smtp.send(to=to, cc=cc, subject=subject, contents=content, attachments=files)
    except:
        traceback.print_exc()
        return False
    return True



def get_sign():
    timestamp = str(round(time.time() * 1000))
    secret = 'SEC12e01f60fb742c3e63b1f45b636bf3246cb566a521dc9d70f70ba9e8d57261c9'
    secret_enc = secret.encode()
    string_to_sign = timestamp + '\n' + secret
    string_to_sign_enc = string_to_sign.encode()
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return timestamp,sign

def send_dd(content,at=None,at_all=False):
    data = {
        "msgtype": "text",
        "text": {
            "content": content
        },
        "at": {
            "atMobiles": at,
            "isAtAll": at_all
        }
    }
    timestamp, sign = get_sign()
    params = {"timestamp": timestamp, 'sign': sign}
    try:
        r = requests.post(url, json=data, params=params)
    except:
        print("钉钉发送消息失败")
        traceback.print_exc()
        return False
    return r.text


if __name__ == '__main__':
    send_mail("挺好的","ok")